const common = require('./common')
const enumerations = require('./enumerations')
const error = require('./error')

export const oauth = {
  
  async checkOauth(utils,_this, needOpenidUri=false) {
  
    // 第一步把error抛出
    if(common.isEmptyString(_this.mchCodeByUrl)
      && common.isEmptyString(_this.cacheMchCode)) {
      // 跳error
      _this.$router.push({
        path: 'error',
        params: ''
      })
    }

    if(!common.isEmptyString(_this.mchCodeByUrl)
      && _this.mchCodeByUrl !== _this.cacheMchCode) {

      _this.cacheMchCode = _this.mchCodeByUrl;
      _this.cacheMchType = "";
      _this.openid = "";
      //清除缓存
      localStorage.setItem('mchCode', _this.mchCodeByUrl)
      localStorage.setItem('type', '')
      localStorage.setItem('openid', '')
      localStorage.setItem('payOpenid', '')

    }

    if(common.isEmptyString(_this.cacheMchType)) {
      _this.cacheMchType = await utils.getMchType(_this.cacheMchCode, _this);
      localStorage.setItem('type', _this.cacheMchType['info']['type'])
    }

    //如果返回type为空则错误
    if(common.isEmptyString(_this.cacheMchType)) {
      _this.$router.push({
        path: 'error',
        params: ''
      })
    }
  
    if(common.isEmptyString(_this.openid)
      && common.isEmptyString(_this.openidByUrl)) {
      
      if(_this.cacheMchType !== enumerations.isNeedGetOauth.yes.key) {
        if(common.isEmptyString(_this.openidByUrl)) {
          _this.$router.push({
            path: 'error',
            params: ''
          })
        }
      }
      
      // 授权
      utils.getOauth(_this.cacheMchCode, _this)
    }
  
    if(!common.isEmptyString(_this.openidByUrl)) {
      _this.openid = _this.openidByUrl
      localStorage.setItem('openid', _this.openidByUrl)
    }
    
  }

}
